package rabbitmq.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Producer
 * @Description
 * ⼀个⽣产者P，多个消费者C1,C2.在多个消息的情况下,WorkQueue会将消息分派给不同的消费者,每消费者都会接收到不同的消息.
 * 特点:消息不会重复,分配给不同的消费者.
 * 适⽤场景:集群环境中做异步处理
 * @Author ZJX
 * @Date 2025/1/7 20:16
 * @Version 1.0
 **/
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
//        1. 创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

//        2. 创建 channel
        Channel channel = connection.createChannel();

//        3. 声明队列
        channel.queueDeclare(Constants.WORK_QUEUE,true,false,false,null);

//        4. 发送消息
        while (true){
            for (int i = 0;i< 10;i++) {
                String message = "Hello, work queue!"+i;
                channel.basicPublish("",Constants.WORK_QUEUE,null,message.getBytes(StandardCharsets.UTF_8));
            }
        }

//        5.结束
//        System.out.println("Hello, RabbitMQ!");
//        connection.close();
    }
}
